package cn.monkey.family.server.domain.sys.file;

import cn.monkey.family.data.Result;
import cn.monkey.family.data.context.Context;
import cn.monkey.family.data.context.RequestContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.IOException;

@Controller
@RequestMapping("file")
public class FileController {

    final FileHandlerContainer fileHandlerContainer;

    public FileController(FileHandlerContainer fileHandlerContainer) {
        this.fileHandlerContainer = fileHandlerContainer;
    }

    @GetMapping("/{moduleName}")
    void download(@Context RequestContext requestContext,
                  @PathVariable("moduleName") String moduleName,
                  HttpServletRequest request,
                  HttpServletResponse response) throws IOException {
        IFileHandler handler = this.fileHandlerContainer.getBean(moduleName);
        if (handler == null) {
            throw new IllegalArgumentException("handler not found");
        }
        handler.download(requestContext, request, response);
    }

    @PostMapping("/{moduleName}")
    Result<?> upload(@Context RequestContext requestContext,
                     @PathVariable("moduleName") String moduleName,
                     MultipartHttpServletRequest request) throws IOException {
        IFileHandler handler = this.fileHandlerContainer.getBean(moduleName);
        if (handler == null) {
            throw new IllegalArgumentException("handler not found");
        }
        return handler.upload(requestContext, request);
    }
}
